package com.example.syl.basaimovie.httputils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by syl on 2017/1/6.
 */
public class HttpUtils {
    //获取网络数据
    public static String getJson(String path){
        HttpURLConnection connection=null;
        try {
            URL url=new URL(path);
            connection= (HttpURLConnection) url.openConnection();
            //连接超时
            connection.setConnectTimeout(5000);
            //读取超时
            connection.setReadTimeout(5000);
            //连接网络
            connection.connect();
            if (connection.getResponseCode()==200){
                InputStream is=connection.getInputStream();
                ByteArrayOutputStream baos=new ByteArrayOutputStream();
                byte[] s=new byte[1024];
                int len=0;
                while((len=is.read(s))!=-1){
                    baos.write(s,0,len);
                }
                byte[] b=baos.toByteArray();
                String p=new String(b);
                return p;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
